<template>
  <div class="app-container">
    <el-form label-position="left" label-width="100px" :model="readerForm" :rules="rules" ref="readerForm">

      <el-form-item label="任务名称" prop="jobName">
        <el-input v-model="readerForm.jobName" />
      </el-form-item>

          <el-form-item label="任务目录" prop="directoryId">

            <el-select
              v-model="readerForm.directoryId"
              clearable
              placeholder="请选择"
              @clear="handleClear"
              ref="selectUpResId"
            >
              <el-option hidden  :value="readerForm.directoryId" :label="upResName">
              </el-option>
              <el-tree
                :data="treeList"
                :props="treeProps"
                :expand-on-click-node="false"
                :check-on-click-node="true"
                @node-click="handleNodeClick"
              >
              </el-tree>
            </el-select>
          </el-form-item>
          <el-form-item label="任务描述" prop="description">
            <el-input v-model="readerForm.description" />
          </el-form-item>
<!--          <el-form-item label="上传附件" prop="filePath">-->
<!--            <el-input v-model="readerForm.filePath" />-->
<!--          </el-form-item>-->
      <el-divider content-position="left">调度信息</el-divider>
      <el-row>
        <el-col :span="24"><div class="grid-content bg-purple-dark">
          <el-form-item label="调度类型" prop="scheduleType">
            <el-radio v-for="(item, index) in dictList('scheduling_type')" :key="index" v-model="readerForm.scheduleType" :label="item.value" @change="handleRadioChange">
              {{ item.label }}
            </el-radio>
          </el-form-item>
        </div>
        </el-col>
        <el-col :span="24"><div class="grid-content bg-purple-dark">
          <el-form-item label="调度时间" prop="scheduleTime" v-if="readerForm.scheduleType=='0'">
            <el-date-picker
              v-model="readerForm.scheduleTime"
              type="datetime"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
        </div>
        </el-col>
        <el-col :span="24"  v-if="readerForm.scheduleType=='1'">
          <el-form-item label="生效日期：" prop="isIncrement" >
            <el-date-picker @change="handleDateRangeChange"
              v-model="dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24"  v-if="readerForm.scheduleType=='1'">
          <el-form-item label="调度时间：" prop="cronExpression" >
            <el-input v-model="readerForm.cronExpression" @focus="dialogCron = true" />
          </el-form-item>
        </el-col>
        <el-col :span="24"><div class="grid-content bg-purple-dark"  v-if="readerForm.scheduleType !='2'">
          <el-form-item label="重跑次数" prop="rerunTime">
            <el-input v-model="readerForm.rerunTime" />
          </el-form-item>
        </div>
        </el-col>
        <el-col :span="24"><div class="grid-content bg-purple-dark" v-if="readerForm.scheduleType !='2'">
          <el-form-item label="提前调度" prop="advanceScheduling">
            <el-radio v-for="(item, index) in dictList('advance_scheduling')" :key="index" v-model="readerForm.advanceScheduling" :label="item.value" >
              {{ item.label }}
            </el-radio>
          </el-form-item>
        </div></el-col>
        <el-col :span="24"><div class="grid-content bg-purple-dark">
          <el-form-item label="调度等级" prop="scheduleLevel">
            <el-radio v-for="(item, index) in dictList('scheduling_level')" :key="index" v-model="readerForm.scheduleLevel" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-form-item>
        </div></el-col>
      </el-row>
      <el-divider content-position="left">高级设置</el-divider>
      <el-row>
        <el-col :span="11"><div class="grid-content bg-purple-dark">
          <el-form-item label="driver内存" prop="driverMemory" label-width="120px">
            <el-input v-model="readerForm.driverMemory" />
          </el-form-item>
        </div>
        </el-col>
        <el-col :span="11" style="margin-left: 1rem"><div class="grid-content bg-purple-dark">
          <el-form-item label="cpu核数" prop="cpuAudit" label-width="120px">
            <el-input v-model="readerForm.cpuAudit" />
          </el-form-item>
        </div></el-col>
        <el-col :span="11"><div class="grid-content bg-purple-dark">
          <el-form-item label="执行单元数量" prop="executeUnitCount" label-width="120px">
            <el-input v-model="readerForm.executeUnitCount" />
          </el-form-item>
        </div></el-col>
        <el-col :span="11" style="margin-left: 1rem"><div class="grid-content bg-purple-dark">
          <el-form-item label="执行单元内存" prop="executeUnitMemory" label-width="120px">
            <el-input v-model="readerForm.executeUnitMemory" />
          </el-form-item>
        </div></el-col>
      </el-row>
    </el-form>
    <el-dialog title="设置执行策略" :visible.sync="dialogCron" :append-to-body="true"
               :close-on-click-modal="false">
      <Crontab @fill="getStr" @hide="dialogCron = false"></Crontab>
    </el-dialog>
  </div>

</template>

<script>
import Crontab from "@/components/Crontab/index.vue"
import {fetchMasterdataDirectoryList} from "@/api/masterdata/masterdataDirectory";
export default {
  name: 'TableMapper',
  components: { Crontab },
  data() {
    return {
      mapperJson: {},
      dialogCron: false,
      temp: {},
      fromTablesList: [],
      toTablesList: [],
      dateRange:[],
      readerForm: {
        jobName: '',//任务名称
        jobGroup: '',//任务目录
        description: '',//任务描述
        lcheckAll: false,
        rcheckAll: false,
        isIndeterminate: true,
        extractionName:'',
        status:'1',

        filePath:'',//附件地址
        scheduleType:'',//调度类型
        scheduleLevel:'',//调度级别
        advanceScheduling:'0',//提前调度
        driverMemory:'',//driver内存
        cpuAudit:'',//cpu核数
        executeUnitCount:'',//执行单元数量
        executeUnitMemory:'',//执行单元内存
        rerunTime:'',//重跑次数
        scheduleTime:'',//调度时间
        cronExpression:'',//corn表达式
        effectTime:'',//开始时间
        failureTime:'',//结束时间
        directoryId:''

      },
      rules: {
        jobName: [{ required: true, message: '任务名称为必填项', trigger: 'change' }],
        directoryId:[{ required: true, message: '任务目录为必填项', trigger: 'change' }],
        scheduleTime:[{ required: true, message: '调度时间为必填项', trigger: 'change' }],
        cronExpression:[{ required: true, message: '调度时间为必填项', trigger: 'change' }],
        scheduleType:[{ required: true, message: '调度类型为必填项', trigger: 'change' }],
        scheduleLevel:[{ required: true, message: '调度等级为必填项', trigger: 'change' }],
        driverMemory:[{ required: true, message: 'driver内存为必填项', trigger: 'change' }],
        cpuAudit:[{ required: true, message: 'cpu核数为必填项', trigger: 'change' }],
        executeUnitCount:[{ required: true, message: '执行单元数量为必填项', trigger: 'change' }],
        executeUnitMemory:[{ required: true, message: '执行单元内存为必填项', trigger: 'change' }],
      },
      selectedOption: 'custom', // 默认选中自定义
      treeQuery: {
        tableName: undefined,
        page: 1,
        limit: this.$store.getters.defaultPageSize,
        ancestralId: '7',
      },
      treeProps: {
        children: 'children',
        label: 'label'
      },
      treeList:[],
      selectedNode: null, // 选中的节点
      treeVisible: false, // 控制树是否可见
      listQuery: {
        jobName: undefined,
        dbType: undefined,
        executeStatus: undefined,
        checkStatus: undefined,
        isSync: undefined,
        directoryId:'',
        page: 1,
        limit: this.$store.getters.defaultPageSize
      },
      upResName:''
    }
  },
  mounted() {
  },
  created() {
    this.getTreeList()
  },
  watch: {
    readerForm: {
      deep: true,
      handler(newData) {
        this.$refs.readerForm.validate(valid => {
          if (valid) {
            // 表单验证通过，执行提交操作

          } else {
            // 表单验证失败，显示错误信息
            console.log('表单验证失败');
          }
        });
        // 当表单数据发生变化时触发自定义事件
        console.log("值改变"+JSON.stringify(newData))
        this.$emit('done', newData);
      }
    }
  },
  methods: {

    //节点点击事件
    handleNodeClick(data){
      // this.readerForm.jobGroup = node.label;
      // this.treeVisible = false; // 隐藏树

      // 这里主要配置树形组件点击节点后，设置选择器的值；自己配置的数据，仅供参考
      this.upResName = data.name
      this.readerForm.directoryId = data.id

      // 选择器执行完成后，使其失去焦点隐藏下拉框的效果
      this.$refs.selectUpResId.blur()
    },
    handleClear() {
      // 将选择器的值置空
      this.upResName = ''
      this.readerForm.directoryId = ''
    },
    getTreeList() {
      this.listLoading = true
      fetchMasterdataDirectoryList(this.treeQuery).then(response => {
        if (response.data.code == 200) {
          this.treeList = response.data.data
          if(this.treeList.length>0){
            this.listQuery.directoryId = this.treeList[0].children[0].id
            this.currentNodekey = this.treeList[0].id;
            this.getList()
            this.$nextTick(() => {
              this.$refs.SlotTree.setCurrentKey(this.currentNodekey); //一定要加这个选中了否则样式没有出来
            });
          }
          this.listLoading = false
        } else {
          this.$message.error(response.data.msg)
        }
        this.listLoading = false
      })
    },
    getStr(str) {
      this.temp.cronExpression = str
      this.readerForm.cronExpression = str
    },
    handleDateRangeChange() {
      // 处理日期范围选择器的值变化事件
      if (Array.isArray(this.dateRange) && this.dateRange.length === 2) {
        this.readerForm.effectTime = this.dateRange[0];
        this.readerForm.failureTime = this.dateRange[1];
        console.log('开始日期:', this.startDate);
        console.log('结束日期:', this.endDate);
      } else {
        this.startDate = '';
        this.endDate = '';
      }
    },
    generateCronExpression() {
      if (this.selectedOption === 'custom') {
        // 根据用户输入生成自定义的 Cron 表达式
        this.cronExpression = `${this.second} ${this.minute} ${this.hour} ${this.dayOfMonth} ${this.month} ${this.dayOfWeek}`;
      } else if (this.selectedOption === 'everyMinute') {
        this.cronExpression = '0 3 0 * * ?';
      } else if (this.selectedOption === 'everyHour') {
        this.cronExpression = '0 3 0 * * ?';
      } else if (this.selectedOption === 'everyDay') {
        this.cronExpression = '0 3 0 * * ?';
      }
      this.readerForm.cronExpression = this.cronExpression;
    },
    handleRadioChange(value) {
      // 处理选项变化事件
      console.log('选项发生变化，新值为：', value);
    },
    rest(){
      this.fromTablesList=[]
      this.toTablesList=[]
      this.readerForm= {
        ltables: [],
        rtables: [],
        lcheckAll: false,
        rcheckAll: false,
        isIndeterminate: true,
        extractionName:'',
        status:'1'
      }
    },
    lHandleCheckAllChange(val) {
      this.readerForm.ltables = val ? this.fromTablesList : []
      this.readerForm.isIndeterminate = false
    },
    rHandleCheckAllChange(val) {
      this.readerForm.rtables = val ? this.toTablesList : []
      this.readerForm.isIndeterminate = false
    },
    lHandleCheckedChange(value) {
      const checkedCount = value.length
      this.readerForm.lcheckAll = checkedCount === this.fromTablesList.length
      this.readerForm.isIndeterminate = checkedCount > 0 && checkedCount < this.fromTablesList.length
    },
    rHandleCheckedChange(value) {
      const checkedCount = value.length
      this.readerForm.rcheckAll = value.length === this.toTablesList.length
      this.readerForm.isIndeterminate = checkedCount > 0 && checkedCount < this.toTablesList.length
    },
    getLTables() {
      return this.readerForm.ltables
    },
    getRTables() {
      return this.readerForm.rtables
    },
    getConfigForm() {
      return this.readerForm
    },
    getName() {
      return this.readerForm
    }
  }
}
</script>
